import { useState, useCallback } from 'react';
import { message } from 'antd';
import { ApiError } from '../utils/request';

export interface ErrorHandlingOptions {
    showNotification?: boolean;
    notificationDuration?: number;
    logError?: boolean;
    throwOnError?: boolean;
}

export interface UseErrorHandlerResult {
    error: ApiError | null;
    setError: (error: ApiError | null) => void;
    clearError: () => void;
    handleError: (error: ApiError | Error) => void;
    isErrored: boolean;
    errorHistory: ApiError[];
}

export function useErrorHandler(options: ErrorHandlingOptions = {}): UseErrorHandlerResult {
    const {
        showNotification = false,
        notificationDuration = 4.5,
        logError = true,
        throwOnError = false
    } = options;

    const [error, setErrorState] = useState<ApiError | null>(null);
    const [errorHistory, setErrorHistory] = useState<ApiError[]>([]);

    const setError = useCallback((newError: ApiError | null) => {
        setErrorState(newError);
        if (newError) {
            setErrorHistory(prev => [newError, ...prev.slice(0, 9)]); // 保留最近10个错误
        }
    }, []);

    const clearError = useCallback(() => {
        setError(null);
    }, [setError]);

    const handleError = useCallback((error: ApiError | Error) => {
        let apiError: ApiError;

        if (error instanceof Error && !(error instanceof ApiError)) {
            apiError = new ApiError(
                error.message,
                undefined,
                undefined,
                undefined,
                error.stack,
                false
            );
        } else {
            apiError = error as ApiError;
        }

        if (logError) {
            console.error('[useErrorHandler]', {
                error: apiError,
                timestamp: new Date().toISOString(),
                url: window.location.href
            });
        }

        setError(apiError);

        if (showNotification) {
            const notificationConfig = {
                content: apiError.message,
                duration: notificationDuration,
                key: `error-${Date.now()}` // 避免重复显示
            };

            // 根据错误类型选择通知方式
            if (apiError.status && apiError.status >= 500) {
                message.error(notificationConfig);
            } else if (apiError.status && apiError.status >= 400) {
                message.warning(notificationConfig);
            } else {
                message.error(notificationConfig);
            }
        }

        if (throwOnError) {
            throw apiError;
        }
    }, [logError, setError, showNotification, notificationDuration, throwOnError]);

    return {
        error,
        setError,
        clearError,
        handleError,
        isErrored: error !== null,
        errorHistory
    };
}